<template>
  <el-container style="display: flex; justify-content: center; height: 100%;">
    <el-card class="box-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20" type="flex" justify="space-between" align="middle">
          <el-col :span="16">
            <el-form-item label="年份" style="width: 200px;">
              <el-select v-model="searchForm.year" placeholder="请选择">
                <el-option value="">全部</el-option>
                <el-option v-for="year in years" :key="year" :label="year" :value="year"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="searchQuery" placeholder="输入比赛名称" clearable @clear="fetchData" @keyup.enter="fetchData"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="text-right">
            <el-button type="success" style="color: red;" @click="AccessControl">权限管理</el-button>
            <el-button type="success"  @click="Documents">上传文件</el-button>
              <el-button type="success" @click="addEvents">新增赛事</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="pagedData" style="width: 100%" stripe class="border-table">
        <el-table-column prop="id" label="序号" width="50"></el-table-column>
        <el-table-column prop="title" label="比赛名称"></el-table-column>
        <el-table-column prop="projectName" label="项目名称"></el-table-column>
        <el-table-column prop="groupname" label="项目组别"></el-table-column>
        <el-table-column label="查看报名信息">
          <template #default="{ row }">
            <el-button :bg="true" link @click="Projectinformation(row.id)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button :bg="true" link @click="edit(row.id)">修改</el-button>
            <el-button :bg="true" link @click="handleSubmit(row.id)">删除</el-button>
            <el-button :bg="true" link @click="showSubmit(row.id)">增删</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[6, 10, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 8px;"></el-pagination>
    </el-card>
  </el-container>
</template>

<script setup>
import { ref, computed, watch, onBeforeMount } from 'vue';
import { useRouter } from 'vue-router';
import { getMatches } from '../js/api';
import axios from 'axios';

const searchQuery = ref('');
const searchForm = ref({ name: '', year: '' });
const currentPage = ref(1);
const pageSize = ref(6);
const total = computed(() => matches.value.length);
const Itemdisplay = ref(true);
const router = useRouter();
const matches = ref([]);
const isLoading = ref(false);
const competitions = ref([]);

const years = computed(() => {
  if (matches.value.length === 0) return [];
  const yearsSet = new Set(matches.value.map(match => match.deadline.slice(0, 4)));
  return Array.from(yearsSet).sort((a, b) => b - a);
});

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});


const fetchMatches = async (ids) => {
  isLoading.value = true;
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/matches/${ids}`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    matches.value = response.data.matchInfos;
  } catch (err) {
    console.error(err.message);
  } finally {
    isLoading.value = false;
  }
};

const token = localStorage.getItem('adminToken');

const matchgroups = [];

onBeforeMount(async () => {
  try {
    const data = await getMatches();
    competitions.value = data.matches;
  } catch (err) {
    console.error(err.message);
  }
  matchgroups.push(...competitions.value.map(item => item.id));
  fetchMatches(matchgroups);
});

// 删除比赛
const handleSubmit = async (event) => {
  ElMessageBox.confirm(`你确定要删除序号为${event}的比赛数据吗？这样您也将删除对应的项目和组别。以及本比赛的所有比赛队伍`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteMatch();
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除'
    });
  });

   // 删除比赛(包括项目和组别)
   const deleteMatch = async () => {
    try {
      const response = await axios.delete(`http://back1.idcfengye.com:15173/match/${event}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (response.data.success) {
        ElMessage.success('删除成功');
        fetchMatches();
        // 处理删除成功的逻辑
      } else {
        console.log('没有数据返回');
        // 处理没有数据返回的逻辑
      }
    } catch (error) {
      console.log(error.response.data);
    }
  };
}

const addEvents = () => {
  Itemdisplay.value = false;
  router.push('/admin/matches');
};
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};
const Projectinformation = (id) => {
  router.push({ path: '/admin/viewproject', query: { id } });
};
const edit = (id) => {
  Itemdisplay.value = false;
  router.push({ name: 'Projectrevise', query: { id } });
};
const fetchData = () => {
  // 搜索函数逻辑
};

//前往权限管理页面
function AccessControl() {
  router.push('/admin/accesscontrol');
}

//前往文件管理页面
function Documents(){
  router.push('/admin/documents');
}

// 搜索表单
const filteredData = computed(() => {
  let data = matches.value;
  if (searchForm.value.year) {
    data = data.filter(item => item.deadline.startsWith(searchForm.value.year));
  }
  if (searchQuery.value) {
    data = data.filter(item => item.title.includes(searchQuery.value));
  }
  return data;
});
watch([searchForm, searchQuery], () => {
  fetchData();
}, { deep: true });
const showSubmit = (id) => {
  Itemdisplay.value = false;
  router.push({ path: '/admin/submit', query: { matchId: id } });
};
</script>

<style scoped>
.box-card {
  background-color: #aacec6;
  display: block;
  width: 99%;
}
.search-form {
  margin-bottom: 20px;
}
.button-icon {
  height: 15px;
  margin-left: -5px;
  margin-top: auto;
}
.text-right {
  text-align: right;
  float: right;
}
.border-table /deep/ .el-table__body-wrapper tbody td {
  border-bottom: 1px solid #000000;
}

.border-table /deep/ .el-table__header-wrapper thead th {
  background-color: #e7e4e4;
  border-bottom: 1px solid #000000;
}
</style>